package com.dianrui.fmi.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dianrui.fmi.R;
import com.dianrui.fmi.activity.TransactionRecordActivity;
import com.dianrui.fmi.adapter.PostionListAdapter;
import com.dianrui.fmi.bean.PositionBean;
import com.dianrui.fmi.event.SwitchAccount;
import com.dianrui.fmi.util.CountDownTimerUtils;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.MyListView;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshScrollView;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;


public class FragmentPostion extends BaseFragment {
    Unbinder unbinder;
    private List<PositionBean> mPositionList = new ArrayList<>();
    private int type;
    private PostionListAdapter postionListAdapter;
    private ProgressDialog mProgressDialog;

    @BindView(R.id.all_close)
    Button allClose;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.balance)
    TextView balance;
    @BindView(R.id.my_scrollview)
    PullToRefreshScrollView myScrollview;
    @BindView(R.id.gross_txt)
    TextView grossTxt;
    @BindView(R.id.total_assets)
    TextView totalAssets;
    @BindView(R.id.advance_charge)
    TextView advanceCharge;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.postion_list)
    MyListView listView;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;


    @Override
    public int getContentViewId() {
        return R.layout.fragment_postion;
    }

    @Override
    public void initView() {
        mProgressDialog = new ProgressDialog(getActivity());
        postionListAdapter = new PostionListAdapter(getActivity(), mPositionList);
        listView.setAdapter(postionListAdapter);
        getBalanaceInfo();
        getPositionList();
        postionListAdapter.setOnButtonClickListener(new PostionListAdapter.CloseClickListener() {
            @Override
            public void onPostionsListCloseClick(final String id) {
                showClose(id);
            }
        });
        myScrollview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        myScrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getBalanaceInfo();
                getPositionList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
        detailsTimer.start();
    }

    CountDownTimerUtils detailsTimer = new CountDownTimerUtils(Long.MAX_VALUE, 6000) {
        @Override
        public void onTick(long millisUntilFinished) {
            getBalanaceInfo();
        }

        @Override
        public void onFinish() {

        }
    };

    @SuppressLint("InflateParams")
    private void showClose(final String id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.RcDialog);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.close_ask, null);
        final AlertDialog dialog = builder.create();
        dialog.setView(view);
        TextView cancel_dialog_ask = view.findViewById(R.id.cancel_dialog_ask);
        final TextView yes_dialog_ask = view.findViewById(R.id.yes_dialog_ask);
        cancel_dialog_ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        yes_dialog_ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ClosePostion(id);
            }
        });
        if (!MyUtil.getActivity(dialog.getContext()).isFinishing()) {
            dialog.show();
        }
    }


    private void ClosePostion(String id) {
        mProgressDialog.setMessage("Closing....");
        mProgressDialog.show();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_id", id);
        jsonObject.addProperty("is_real", "2");
        OkHttpUtils.getInstance().postWithMemberToken(Url.CLOSE, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject &&!isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                getBalanaceInfo();
                                getPositionList();
                            } else {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mProgressDialog.dismiss();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    @Override
    public void getData() {
    }

    //获取余额（当前余额和已提现）
    private void getBalanaceInfo() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("is_real", "2");
        OkHttpUtils.getInstance().postWithMemberToken(Url.GETBALACE, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                myScrollview.onRefreshComplete();
                                totalAssets.setText(jsonObject.optJSONObject("data").optString("equity"));
                                total.setText(jsonObject.optJSONObject("data").optString("total"));
                                balance.setText(jsonObject.optJSONObject("data").optString("balance"));
                                number.setText(jsonObject.optJSONObject("data").optString("order_count"));
                                if (jsonObject.optJSONObject("data").optString("order_count").equals("0")) {
                                    allClose.setEnabled(false);
                                } else {
                                    allClose.setEnabled(true);
                                }
                                if (jsonObject.optJSONObject("data").optString("gross").contains("-")) {
                                    grossTxt.setTextColor(getResources().getColor(R.color.green));
                                    grossTxt.setText(jsonObject.optJSONObject("data").optString("gross"));
                                } else {
                                    grossTxt.setTextColor(getResources().getColor(R.color.red_deep));
                                    grossTxt.setText(jsonObject.optJSONObject("data").optString("gross"));
                                }
                                advanceCharge.setText(jsonObject.optJSONObject("data").optString("margin"));
                            } else {
                                myScrollview.onRefreshComplete();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    myScrollview.onRefreshComplete();

                }
            }
        });


    }

    private void getPositionList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("type", "2");
        jsonObject.addProperty("is_real", "2");
        OkHttpUtils.getInstance().postWithMemberToken(Url.SIMULATED_LIST, jsonObject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                myScrollview.onRefreshComplete();
                                if (mPositionList != null) {
                                    mPositionList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        PositionBean positionBean = new PositionBean();
                                        positionBean.order_id = jsonArray.optJSONObject(i).optString("order_id");
                                        positionBean.createtime = jsonArray.optJSONObject(i).optString("create_time");
                                        positionBean.price = jsonArray.optJSONObject(i).optString("price");
                                        positionBean.start_price = jsonArray.optJSONObject(i).optString("start_price");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.earnings = jsonArray.optJSONObject(i).optString("earnings");
                                        positionBean.full_symbol = jsonArray.optJSONObject(i).optString("full_symbol");
                                        positionBean.symbol = jsonArray.optJSONObject(i).optString("symbol");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.name = jsonArray.optJSONObject(i).optString("name");
                                        positionBean.direction = jsonArray.optJSONObject(i).optString("direction");
                                        positionBean.service_charge = jsonArray.optJSONObject(i).optString("service_charge");
                                        positionBean.mix_price = jsonArray.optJSONObject(i).optString("mix_price");
                                        positionBean.postion = jsonArray.optJSONObject(i).optString("overnight_fee");
                                        positionBean.margin = jsonArray.optJSONObject(i).optString("margin");
                                        positionBean.total = jsonArray.optJSONObject(i).optString("total");
                                        mPositionList.add(positionBean);
                                    }
                                    if (postionListAdapter != null) {
                                        postionListAdapter.refresh(mPositionList);
                                    }


                                } else {
                                    myScrollview.onRefreshComplete();
                                }
                            } else {
                                myScrollview.onRefreshComplete();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (mPositionList.size() <= 0) {
                        emptyView.setVisibility(View.VISIBLE);
                        listView.setVisibility(View.GONE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        listView.setVisibility(View.VISIBLE);
                    }
                } else {
                    myScrollview.onRefreshComplete();
                }

            }
        });
    }


    private void AllClosePostion() {
        mProgressDialog.setMessage("Closing....");
        mProgressDialog.show();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("is_real", "2");
        OkHttpUtils.getInstance().postWithMemberToken(Url.CLOSE, jsonObject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                getBalanaceInfo();
                                getPositionList();
                            } else {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mProgressDialog.dismiss();
                    ToastUtil.showToast(getString(R.string.net_error));

                }
            }
        });
    }


    @OnClick({R.id.all_close, R.id.light_account_layout,R.id.deal_record_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.all_close:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.RcDialog);
                View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.close_allask, null);
                final AlertDialog dialog = builder.create();
                dialog.setView(view1);
                TextView cancel_dialog_ask = view1.findViewById(R.id.cancel_dialog_ask);
                final TextView yes_dialog_ask = view1.findViewById(R.id.yes_dialog_ask);
                cancel_dialog_ask.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                yes_dialog_ask.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        AllClosePostion();
                    }
                });
                if (!MyUtil.getActivity(dialog.getContext()).isFinishing()) {
                    dialog.show();
                }
                break;
            case R.id.light_account_layout:
                EventBus.getDefault().post(new SwitchAccount());
                getActivity().finish();
                break;

            case R.id.deal_record_layout:
                JumpActivitys(TransactionRecordActivity.class);
                break;

                default:
                    break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (detailsTimer != null) {
            detailsTimer.cancel();
        }
    }




}
